package com.tmc.service.baseinfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.constant.CacheConstant;
import com.tmc.dao.impl.ContinentDaoImpl;
import com.tmc.dao.impl.CountryDaoImpl;
import com.tmc.entity.baseinfo.Airport;
import com.tmc.entity.baseinfo.Continent;
import com.tmc.entity.baseinfo.Country;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.ObjectUtil;

@Service
@Transactional
public class ContinentServiceImpl {

	@Autowired
	private ContinentDaoImpl dao;

	@Autowired
	private CountryDaoImpl countryDao;
	
	@Autowired
	private CacheServiceImpl cache;
	
	private static String all_key = "KEY_CONTINENT_ALL";
	
	private static String map_key = "KEY_CONTINENT_ALL_MAP";

	private Log logger = LogFactory.getLog(this.getClass());

	public Pagination<Continent> findByCon(ContextInfo context, Continent cond, int pageIndex, int pageSize) {
		Pagination<Continent> result = dao.findByCon(context, cond, pageIndex, pageSize);
		this.setExtInfo(result);
		return result;
	}

	public Continent getByCode(String code){
		if (ObjectUtil.noText(code)){
			return null;
		}
		List<Continent> continents = this.findAllFromCache();
		for (Continent continent : continents){
			if (continent.getContinentCode().equals(code)){
				return continent;
			}
		}
		return null;
	}
	
	public String getNameByCode(String code){
		Continent bean = this.getByCode(code);
		if (bean == null){
			return code;
		}
		return bean.getContinentName();
	}

	public List<Continent> findAllFromCache() {
		if (cache.get(CacheConstant.CACHE_NAME_600, all_key) != null) {
			return (List<Continent>) cache.get(CacheConstant.CACHE_NAME_600, all_key);
		}
		List<Continent> list = dao.findAll();
		cache.put(CacheConstant.CACHE_NAME_600, all_key, list);
		return list;
	}

	public Map<String, Continent> findMapFromCache(ContextInfo context) {
		if (cache.get(CacheConstant.CACHE_NAME_600, map_key) != null) {
			return (Map<String, Continent>) cache.get(CacheConstant.CACHE_NAME_600, map_key);
		}
		Map<String, Continent> map = this.toMap(this.findAllFromCache());
		cache.put(CacheConstant.CACHE_NAME_600, map_key, map);
		return map;
	}

	private Map<String, Continent> toMap(List<Continent> continents) {
		Map<String, Continent> map = new HashMap<String, Continent>();
		for (Continent continent : continents) {
			map.put(continent.getContinentCode(), continent);
		}
		return map;
	}

	@CacheEvict(value = CacheConstant.CACHE_NAME_600, key = "'KEY_CONTINENT_ALL'")
	public CommonResult delete(ContextInfo context, Long continentId) {
		Continent continent = dao.getById(continentId);
		if (continent != null) {
			ObjectUtil.updateBaseInfo(continent, context);
			continent.setEnabledFlag("N");
			dao.update(continent);
		}
		return CommonResult.makeSuccess("删除成功！");
	}

	public Continent getById(ContextInfo context, Long continentId) {
		return dao.getById(continentId);
	}

	@CacheEvict(value = CacheConstant.CACHE_NAME_600, key = "'KEY_CONTINENT_ALL'")
	public CommonResult save(ContextInfo context, Continent continent) {
		CommonResult check = this.check(continent);
		if (!check.isSuccess()) {
			return check;
		}
		// 国家相关赋值
		CommonResult result = this.setCountryInfos(context, continent);
		if (!result.isSuccess()) {
			return result;
		}
		// 保存
		if (continent.getContinentId() == null) {
			ObjectUtil.setBaseInfo(continent, context);
			dao.insert(continent);
		} else {
			// 编辑
			try {
				Continent dbContinent = dao.getById(continent.getContinentId());
				if (dbContinent != null) {
					ObjectUtil.copyProperties(continent, dbContinent, new String[] { "createdBy", "creationDate",
							"continentId", "enabledFlag" });
				}
				ObjectUtil.updateBaseInfo(dbContinent, context);
				dao.update(dbContinent);
			} catch (Exception e) {
				logger.error("拷贝对象错误！", e);
				return CommonResult.makeFail("拷贝对象错误！");
			}
		}
		return CommonResult.makeSuccess();
	}
	
	private CommonResult setCountryInfos(ContextInfo context, Continent continent){
		List<Country> countrys = null;
		try {
			countrys = this.getCountrysByValues(context, continent.getCountryNames());
		} catch (Exception e) {
			return CommonResult.makeFail(e.getMessage());
		}
		if (countrys != null && !countrys.isEmpty()) {
			String codes = "", names = "";
			for (Country country : countrys) {
				codes += country.getCountryCode() + "/";
				names += country.getCountryName() + "/";
			}
			continent.setCountryCodes(codes);
			continent.setCountryNames(names);
		}
		return CommonResult.makeSuccess();
	}

	private List<Country> getCountrysByValues(ContextInfo context, String countryNames) throws Exception {
		String[] values = null;
		if (countryNames.contains("|")) {
			values = countryNames.split("\\|");
		} else {
			values = countryNames.split("/");
		}
		if (values == null || values.length == 0) {
			return null;
		}
		List<Country> countrys = new ArrayList<Country>();
		for (String value : values) {
			value = value.replace(" ", "");
			Country country = this.getCountryByValue(context, value);
			if (country == null) {
				logger.error("未找到国家：" + value);
				throw new Exception("未找到国家：" + value);
			}
			countrys.add(this.getCountryByValue(context, value));
		}
		return countrys;
	}

	private Country getCountryByValue(ContextInfo context, String value) {
		Country country = countryDao.getByCode(context, value);
		if (country == null) {
			country = countryDao.getByName(context, value);
		}
		return country;
	}

	private CommonResult check(Continent Continent) {
		if (!ObjectUtil.hasText(Continent.getContinentName())) {
			return CommonResult.makeFail("大洲名字不能为空！");
		}
		return CommonResult.makeSuccess();
	}

	private void setExtInfo(Pagination<Continent> result) {
		// TODO Auto-generated method stub

	}

	public void updateFromCountry(ContextInfo context) {
		List<Country> citys = countryDao.findAll();
		for (Country city : citys) {
			if (ObjectUtil.hasText(city.getContinentCode())) {
				Continent dbContinent = dao.getByCode(context, city.getContinentCode());
				if (dbContinent == null) {
					System.out.println("添加大洲" + city.getContinentCode());
					Continent Continent = new Continent();
					Continent.setContinentCode(city.getContinentCode());
					Continent.setContinentName(city.getContinentName());
					Continent.setContinentNameEn(city.getContinentNameEn());
					ObjectUtil.setBaseInfo(Continent, context);
					dao.insert(Continent);
				}
			}
		}
		System.out.println("处理完毕");
	}

}
